# -*- coding: utf-8 -*-
import codecs
import sys
from pathlib import Path

from osgeo import ogr, osr
from qgis.PyQt.QtWidgets import QApplication, QMessageBox
from qgis.PyQt.QtWidgets import QMainWindow
import re
from shp2txt_ui import *
import os
import sys


# proj_data_dir = os.path.dirname(__file__)
# proj_data_dir = os.path.join(proj_data_dir, "proj")
# os.environ["PROJ_LIB"] = proj_data_dir

def new_framing_code(latitude, longitude, code):
    first = chr(int(latitude / 4) + 65)
    second = int(longitude / 6) + 31
    if code == 'B':
        third = int(2 - (latitude % 4) // 2)
        fourth = int((longitude % 6) // 3 + 1)
    elif code == 'C':
        third = int(4 - (latitude % 4) // 1)
        fourth = int((longitude % 6) // 1.5 + 1)
    elif code == 'D':
        third = int(12 - (latitude % 4) // (1 / 3.0))
        fourth = int((longitude % 6) // 0.5 + 1)
    elif code == 'E':
        third = int(24 - (latitude % 4) // (1 / 6.0))
        fourth = int((longitude % 6) // 0.25 + 1)
    elif code == 'F':
        third = int(48 - (latitude % 4) // (1 / 12.0))
        fourth = int((longitude % 6) // 0.125 + 1)
    elif code == 'G':
        third = int(96 - (latitude % 4) // (1 / 24.0))
        fourth = int((longitude % 6) // 0.0625 + 1)
    return f"{first}{second:02}{code}{third:03}{fourth:03}"


shp_path = r"D:\用户\Documents\WeChat Files\wxid_1byvcv44v5z622\FileStorage\File\2023-11\桑植县2023成片开发\桑植2023成片开发.shp"
txt_path = r"C:\Users\Administrator\Desktop\test.txt"


class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)
        self.pushButton.clicked.connect(self.pushButton_clicked)
        self.vlayer_mQgsFileWidget.fileChanged.connect(self.on_layerchange)

    def on_layerchange(self, e):
        if e != '':
            if e.endswith('.shp'):
                driver = ogr.GetDriverByName("ESRI Shapefile")
                dataSource = driver.Open(e, 0)
                if dataSource is None:
                    print('could not open')
                    sys.exit(1)
                layer = dataSource.GetLayer(0)
                # 获取图层属性表定义
                featuredefn = layer.GetLayerDefn()
                # 获取属性表中字段数
                fieldcount = featuredefn.GetFieldCount()
                # 获取字段属性名
                name = []
                for attr in range(fieldcount):
                    fielddefn = featuredefn.GetFieldDefn(attr)
                    # print("%s: %s" % (fielddefn.GetNameRef(), fielddefn.GetFieldTypeName(fielddefn.GetType())))
                    name.append(fielddefn.GetNameRef())
                print(name)
                self.region_name_comboBox.clear()
                self.region_name_comboBox.addItems(name)
                self.land_class_comboBox.clear()
                self.land_class_comboBox.addItems(name)

    def pushButton_clicked(self):
        shp_path = self.vlayer_mQgsFileWidget.filePath()
        pression = int(self.pression_lineEdit.text())
        region_name_field = self.region_name_comboBox.currentText()
        land_class_field = self.land_class_comboBox.currentText()
        self.run_algorithm(shp_path, region_name_field, land_class_field, pression)

    def run_algorithm(self, shp_path, region_name_field, land_class_field, pression=6):
        txt_path = Path(shp_path).with_suffix('.txt')
        driver = ogr.GetDriverByName("ESRI Shapefile")
        dataSource = driver.Open(shp_path)
        if dataSource is None:
            print('could not open')
            sys.exit(1)
        layer = dataSource.GetLayer(0)
        n = layer.GetFeatureCount()

        contents = []
        for feat_index in range(layer.GetFeatureCount()):
            feat = layer.GetFeature(feat_index)
            region_name = feat.GetField(region_name_field)
            geom = feat.geometry()
            print(geom)
            region_area = geom.GetArea() / 10000

            point_count = 0
            feat_contents = []
            sourceSR = layer.GetFeature(0).GetGeometryRef().GetSpatialReference()
            if sourceSR.GetName()[-1] == 'E':
                tape_number = int(int(re.search(r'CM\D*(\d*)E', sourceSR.GetName()).group(1)) / 3)
                tape_coefficient = tape_number
            else:
                tape_number = int(re.search(r'zone\D*(\d*)', sourceSR.GetName()).group(1))
                tape_coefficient = 0
            for geom_index in range(geom.GetGeometryCount()):
                point_count += feat.geometry().GetGeometryRef(geom_index).GetPointCount()
                points = feat.geometry().GetGeometryRef(geom_index).GetPoints()
                for point_index, point in enumerate(points):
                    if point_index == len(points) - 1:
                        feat_contents.append(f'J01,{geom_index + 1},{point[1]:.0{pression}f},'
                                             f'{point[0] + tape_coefficient * 1000000:.0{pression}f}')
                    else:
                        feat_contents.append(
                            f'J{point_index + 1:02},{geom_index + 1},{point[1]:.0{pression}f},{point[0] + tape_coefficient * 1000000:.0{pression}f}')
            sourceSR = layer.GetFeature(0).GetGeometryRef().GetSpatialReference()
            targetSR = osr.SpatialReference()
            targetSR.ImportFromWkt(
                'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AXIS["Latitude",NORTH],AXIS["Longitude",EAST],AUTHORITY["EPSG","4326"]]')  # Geo WGS84
            # print(sourceSR,targetSR)
            coordTrans = osr.CoordinateTransformation(sourceSR, targetSR)
            geom.Transform(coordTrans)

            lon, lat = geom.GetGeometryRef(0).GetPoints()[0]
            framing_code = new_framing_code(lon, lat, 'G')

            region_code = feat_index + 1
            land_class_name = feat.GetField(land_class_field)
            land_class_code = ''
            # land_class_code = feat.GetField('land_code') if feat.GetField('land_code') else ''
            feat_contents.insert(0, f'{point_count},{region_area:.{4}f},{region_code},{region_name},面'
                                    f','
                                    f',{land_class_name},'
                                    f'{land_class_code},@')
            contents.append(feat_contents)
        if os.path.exists('./header.txt'):
            with codecs.open('./header.txt', 'r') as f:
                file_header = [line.strip() for line in f.readlines()]
        else:
            file_header = ["[属性描述]", "格式版本号=1.01版本", "数据生产单位=null", "数据生产日期=2023-8-30",
                           "坐标系=2000国家大地坐标系", "几度分带=3", "投影类型=高斯克吕格",
                           "计量单位=米", "带号=37", "精度=0.001", "转换参数= , , , , , ,", "[地块坐标]"]
        file_header[9] = f'精度={(1 / (10 ** pression)):.0{pression}f}'
        # print(sourceSR)
        file_header[8] = f"带号={tape_number}"
        contents.insert(0, file_header)
        with open(txt_path, 'w') as f:
            for content in contents:
                f.write('\n'.join(content))
                f.write('\n')
            QMessageBox.information(self, '提示', '已生成文件')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainwindow = MainWindow()
    mainwindow.show()
    sys.exit(app.exec_())

# "D:\Program Files\QGIS-LTR\bin\python-qgis-ltr.bat" -m PyInstaller -y -w --add-data="D:\Program Files\QGIS-LTR\apps\qgis-ltr\plugins;qgis\plugins" --add-data="D:\Program Files\QGIS-LTR\apps\Python39\Lib\site-packages\PyQt5\*.pyd;PyQt5" --add-data="D:\Program Files\QGIS-LTR\apps\qt5\plugins\styles;PyQt5\Qt5\plugins\styles" --add-data="D:\Program Files\QGIS-LTR\apps\qt5\plugins\iconengines;PyQt5\Qt5\plugins\iconengines" --add-data="D:\Program Files\QGIS-LTR\apps\qt5\plugins\imageformats;PyQt5\Qt5\plugins\imageformats" --add-data="D:\Program Files\QGIS-LTR\apps\qt5\plugins\platforms;PyQt5\Qt5\plugins\platforms" --add-data="D:\Program Files\QGIS-LTR\apps\qt5\plugins\platformthemes;PyQt5\Qt5\plugins\platformthemes" shp2txt.py
